#include "request.h"

#include <QJsonDocument>
#include <QNetworkRequest>
#include <QUrlQuery>

Request::Request()
#if QT_VERSION >= QT_VERSION_CHECK(5,15,0)
    : m_timeout(QNetworkRequest::DefaultTransferTimeoutConstant)
#else
    : m_timeout(30000)
#endif
{

}

Request::Request(QString url)
#if QT_VERSION >= QT_VERSION_CHECK(5,15,0)
    : m_timeout(QNetworkRequest::DefaultTransferTimeoutConstant)
#else
    : m_timeout(30000)
#endif
{
    m_url = url;
}

QUrl Request::url()
{
    return QUrl(m_url);
}

QUrl Request::queryUrl()
{
    QUrl tmp = url();
    QUrlQuery tmp_query;

    QList<QPair<QString, QString>> tmp_items = QUrlQuery(tmp.query()).queryItems();
    tmp_items <<  m_query.queryItems();

    foreach (auto var, tmp_items) {
        tmp_query.addQueryItem(var.first, var.second);
    }

    tmp.setQuery(tmp_query);
    return tmp;
}

void Request::addQuery(const QString &key, const QString &value)
{
    m_query.removeQueryItem(key);
    m_query.addQueryItem(key, value);
}

void Request::setUrl(const QString &newUrl)
{
    m_url = newUrl;
    QUrl url(newUrl);
    setHeader("Host", url.host());
}

void Request::setData(const QString &data)
{
    m_data = data;
}

void Request::setData(const QVariantMap &data)
{
    m_data = QJsonDocument::fromVariant(data).toJson();
}

void Request::setData(QVariantList &data)
{
    m_data = QJsonDocument::fromVariant(data).toJson();
}

QByteArray Request::data()
{
    return m_data.toUtf8();
}

void Request::setHeader(const QString &header, const QString &value)
{
    m_headers.insert(header.toUtf8(), value.toUtf8());
}

void Request::setHeaders(const QMap<QString, QString> &newHeaders)
{
    m_headers = newHeaders;
}

QMap<QString, QString> Request::headers() const
{
    return m_headers;
}

QVariantMap Request::variantHeaders() const
{
    return m_variantHeaders;
}

void Request::setVariantHeaders(const QVariantMap &newVariantHeaders)
{
    m_variantHeaders = newVariantHeaders;
}


int Request::timeout() const
{
    return m_timeout;
}

void Request::setTimeout(int timeout)
{
    m_timeout = timeout;
}

QString Request::timeoutMessage() const
{
    return m_timeoutMessage;
}

void Request::setTimeoutMessage(const QString &newTimeoutMessage)
{
    m_timeoutMessage = newTimeoutMessage;
}
